﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FineUI;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class Manager_Main : System.Web.UI.PageEx
{
    private string strPageCode = "S0000A";
    private string strLoginResult = string.Empty;
    private int iLoginUserId = 0;
    Model.DbSystem dbSystem = Dal.DbSystemDal.Select(1);

    protected void Page_Load(object sender, EventArgs e)
    {
        int.TryParse(Convert.ToString(Session["UserId"]), out iLoginUserId);
        if (!DalEx.DbManagerEx.CheckLoginRight(UserType,UserId, strPageCode, ref strLoginResult))
        {
            FineUI.Alert.Show(strLoginResult, FineUI.MessageBoxIcon.Warning);
            Response.Redirect("Login.aspx");
        }
        // 注册客户端脚本，服务器端控件ID和客户端ID的映射关系
        JObject ids = GetClientIDS(tabMainStrip);
        if (!Page.IsPostBack)
        {
            string idsScriptStr = String.Format("window.IDS={0};", ids.ToString(Newtonsoft.Json.Formatting.None));
            PageContext.RegisterStartupScript(idsScriptStr);
            LoadTreeData();
        }
    }
    protected void trLeftMenu_NodeCommand(object sender, FineUI.TreeCommandEventArgs e)
    {
        string strNodeId = e.Node.NodeID;
        Model.DbSysMenu sysMenu = DalEx.DBSysMenuEx.Select(Convert.ToInt32(strNodeId));
        if (sysMenu != null && sysMenu.SmUrl != "#")
        {
            FineUI.PageContext.RegisterStartupScript(tabMainStrip.GetRemoveTabReference("t_" + strNodeId));
            FineUI.PageContext.RegisterStartupScript(tabMainStrip.GetAddTabReference("t_" + strNodeId, sysMenu.SmUrl, sysMenu.SmName, sysMenu.SmIcon, true));
        }
    }
    #region 绑定树形菜单
    /// <summary>
    /// 加载树形菜单数据
    /// </summary>
    private void LoadTreeData()
    {
        setMeta();
        DataSet ds = Dal.DbSysMenuDal.Select(" and smStatus=1 Order by smOrder asc");
        ds.Relations.Add("TreeRelation", ds.Tables[0].Columns["smCode"], ds.Tables[0].Columns["smUpCode"]);
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            if (row.IsNull("smUpCode"))
            {
                FineUI.TreeNode node = new FineUI.TreeNode();
                node.NodeID = row["smId"].ToString();
                node.Text = row["smName"].ToString();
                //node.NavigateUrl = row["smUrl"].ToString();
                node.Expanded = true;
                node.EnablePostBack = true;
                trLeftMenu.Nodes.Add(node);
                ResolveSubTree(row, node);
            }
        }
    }
    /// <summary>
    /// 绑定树形菜单
    /// </summary>
    /// <param name="dataRow"></param>
    /// <param name="treeNode"></param>
    private void ResolveSubTree(DataRow dataRow, FineUI.TreeNode treeNode)
    {
        DataRow[] rows = dataRow.GetChildRows("TreeRelation");
        if (rows.Length > 0)
        {
            treeNode.Expanded = true;
            foreach (DataRow row in rows)
            {
                FineUI.TreeNode node = new FineUI.TreeNode();
                node.NodeID = row["smId"].ToString();
                node.Text = row["smName"].ToString();
                //node.NavigateUrl = row["smUrl"].ToString();
                node.Expanded = true;
                node.EnablePostBack = true;
                treeNode.Nodes.Add(node);
                ResolveSubTree(row, node);
            }
        }
    }

    #endregion
    protected void btnChangePwd_Click(object sender, EventArgs e)
    {
        winChangePwd.Hidden = false;
    }
    protected void winMenu_Close(object sender, WindowCloseEventArgs e)
    {
        winChangePwd.Hidden = true;
    }
    protected void btnChangePwd1_Click(object sender, EventArgs e)
    {
        string strOldPwd = txtOldPwd.Text.Trim();
        string strNewPwd = txtNewPwd.Text.Trim();
        string strReNewPwd = txtReNewPwd.Text.Trim();
        if (strNewPwd.Equals(strReNewPwd))
        {
            Model.DbManager manager = DalEx.DbManagerEx.Select(iLoginUserId);
            if (manager != null && manager.MPwd.Equals(SqlHelper.MD5(strOldPwd, 32)))
            {
                manager.MPwd = SqlHelper.MD5(strNewPwd, 32);
                if (DalEx.DbManagerEx.Update(manager) > 0)
                {
                    Model.DbActionLog actionLog = new Model.DbActionLog();
                    actionLog.AUId = UserId.ToString();
                    actionLog.ADateTime = DateTime.Now;
                    actionLog.ANote = UserName + "对用户(" + manager.MUser + "),密码修改！";
                    actionLog.AIpaddress = WebBase.GetClientIP.getIPAddress2Num().ToString();
                    actionLog.AOS = WebBase.Comm.GetOS;
                    actionLog.ABrowse = WebBase.Comm.GetUserBrowser;
                    Dal.DbActionLogDal.Insert(actionLog);

                    Alert.ShowInTop("密码已修改，请重新登录！", MessageBoxIcon.Information);
                    Logout();
                }
            }
            else
            {
                Alert.ShowInTop("输入的旧密码有误！", MessageBoxIcon.Warning);
            }
        }
        else
        {
            Alert.ShowInTop("两次输入的密码不一致！", MessageBoxIcon.Warning);
        }
    }

    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Logout();
    }

    private void Logout()
    {
        Session["UserId"] = string.Empty;
        Session["UserName"] = string.Empty;
        Response.Redirect("Login.aspx");
    }
    private JObject GetClientIDS(params ControlBase[] ctrls)
    {
        JObject jo = new JObject();
        foreach (ControlBase ctrl in ctrls)
        {
            jo.Add(ctrl.ID, ctrl.ClientID);
        }

        return jo;
    }
    private void setMeta()
    {
        HtmlMeta keywords = new HtmlMeta(); // keywords
        HtmlMeta description = new HtmlMeta(); // description

        keywords.Name = "keywords";
        description.Name = "description";

        if (dbSystem != null)
        {
            this.Title = dbSystem.STitle+"后台管理系统";
            keywords.Content = dbSystem.SKeywords;
            description.Content = dbSystem.SDescription;
        }
        tblbWebName.Text = "《" + dbSystem.SWebName + "》--后台管理系统";
        Page.Header.Controls.Add(keywords);
        Page.Header.Controls.Add(description);
    }
}
